using UnityEngine;

public class LanguageManager : MonoBehaviour
{
    public static LanguageManager Instance;

    // 引用语言数据（ScriptableObject）
    public LanguageData languageData;

    // 当前游戏语言，默认英语
    public SystemLanguage currentLanguage = SystemLanguage.English;

    void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);

            // 加载保存的语言设置
            currentLanguage = (SystemLanguage)PlayerPrefs.GetInt("GameLanguage", (int)SystemLanguage.English);
        }
        else
        {
            Destroy(gameObject);
        }
    }

    public string GetText(string key)
    {
        if (languageData == null)
        {
            Debug.LogError("LanguageData not assigned!");
            return key;
        }
        return languageData.GetText(key, currentLanguage);
    }

    //public void SwitchLanguage(SystemLanguage newLanguage)
    //{
    //    currentLanguage = newLanguage;
    //    PlayerPrefs.SetInt("GameLanguage", (int)currentLanguage);
    //    PlayerPrefs.Save();

    //    // 向所有游戏对象发送语言变更通知（可选）
    //    // SendMessageOptions.DontRequireReceiver 表示不要求接收方必须有对应方法
    //    //BroadcastMessage 是 Unity 提供的一种消息传递机制，用于向 当前 GameObject 及其 所有子对象 发送消息，调用匹配名称的方法。
    //    BroadcastMessage("OnLanguageChanged", SendMessageOptions.DontRequireReceiver);
    //}

    public void ToggleLanguage()
    {
        // 简化的切换逻辑：只在英语和简体中文间切换
        currentLanguage = (currentLanguage == SystemLanguage.Chinese ||
                          currentLanguage == SystemLanguage.ChineseSimplified)
                          ? SystemLanguage.English
                          : SystemLanguage.Chinese;

        PlayerPrefs.SetInt("GameLanguage", (int)currentLanguage);
        PlayerPrefs.Save();

        // 更新所有文本
        BroadcastMessage("OnLanguageChanged", SendMessageOptions.DontRequireReceiver);

        // 更新按钮文本
        UpdateButtonText();
    }

    public void RefreshLanguage()
    {
        // 更新所有文本
        BroadcastMessage("OnLanguageChanged", SendMessageOptions.DontRequireReceiver);
    }

    // 更新按钮文本的方法
    private void UpdateButtonText()
    {
        var buttons = FindObjectsOfType<LanguageButton>();
        foreach (var button in buttons)
        {
            button.UpdateButtonText();
        }
    }
}